package com.qf.commons.mysql.webintercepter;

import com.qf.commons.mysql.utils.QphonePage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: 分页的拦截器 简化web开发
 * author: Ken
 * 公众号：Java架构栈
 */
@Slf4j
public class PageIntercepter extends HandlerInterceptorAdapter {

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的参数
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (pageNum != null && pageSize != null) {
            log.debug("[page intercepter] 分页拦截器生效 - pageNum:{} pageSize:{}", pageNum, pageSize);
            try {
                Integer pNum = Integer.parseInt(pageNum);
                Integer pSize = Integer.parseInt(pageSize);

                //设置分页参数，表示进行了分页
                QphonePage.setPage(pNum, pSize);
            } catch (Throwable e){
                return true;
            }
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal
        log.debug("[page intercepter] 分页拦截器后置处理，清除ThreadLocal");
        QphonePage.clear();
    }
}
